package com.suxii.frpclient;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;

import com.suxii.frpclient.utils.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

public class FrpServer {

    private final Context context;

    public FrpServer(Context context) {
        this.context = context;
    }

    public void startFrpc() throws Exception{
        ApplicationInfo info = context.getPackageManager().getApplicationInfo(
                context.getPackageName(),
                PackageManager.GET_SHARED_LIBRARY_FILES
        );

        String filename = "libfrpc.so";

        /*String path = info.nativeLibraryDir + "/" + filename;
        Log.e("stdout",path);
        File file = new File(path);
        boolean f = file.exists();
        Log.e("stdout","file is exist "+f);*/

        String path2 = FileUtil.initConfigFile(context);

        String path = context.getFilesDir().getPath() + "/frpc.toml";
        // 创建并启动新线程来执行命令
        Thread thread = new Thread(() -> {
            try {
                Log.e("stdout",info.nativeLibraryDir + "/" + filename + " -c "+ path);
                runCommand(info.nativeLibraryDir + "/" + filename + " -c "+ path, new String[]{}, context.getFilesDir());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        thread.start();

        // 显示Toast消息
        Toast.makeText(context,"执行命令", Toast.LENGTH_SHORT).show();


    }


    private void runCommand(String command, String[] envp, File workDir) throws Exception{

        ProcessBuilder pb = new ProcessBuilder(command.split(" "));
        pb.directory(workDir);
        Map<String, String> env = pb.environment();
        if (envp != null) {
            for (String s : envp) {
                String[] keyValue = s.split("=");
                if (keyValue.length == 2) {
                    env.put(keyValue[0], keyValue[1]);
                }
            }
        }
        Process process = pb.start();
        InputStream stdout = process.getInputStream();
        new Thread(()->{
            try (BufferedReader br = new BufferedReader(new InputStreamReader(stdout))){
                String s;
                while ((s = br.readLine()) != null){
                    Log.i("stdout",s);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }).start();
    }
}
